package com.xiaoke.liantongdemo.widget;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import com.xiaoke.liantongdemo.bean.Business;

import android.content.Context;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

public class BusinessesLayout extends HorizontalScrollView {
	
	private Context context;
	private ArrayList<Business> businessList;
	private boolean isAutoScolling;
	
	private Timer timer = new Timer();
	
	private TimerTask timerTask;

	public BusinessesLayout(Context context, ArrayList<Business> businessList) {
		super(context);
		this.context = context;
		this.businessList = businessList;
		init();
	}
	
	private void init(){
		setHorizontalScrollBarEnabled(false);
		LinearLayout layout = new LinearLayout(context);
		for(Business business : businessList){
			layout.addView(new BusinessLayout(context, business));
		}
		addView(layout);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		super.onTouchEvent(ev);
		if(ev.getAction() == MotionEvent.ACTION_UP){
			timerTask = new ScrollTimerTask();
			timer.schedule(timerTask, 100);
			isAutoScolling = true;
		}else{
			isAutoScolling = false;
		}
		return true;
		
	}
	
	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		super.onScrollChanged(l, t, oldl, oldt);
		System.out.println("onScrollChanged");
		if(isAutoScolling){
			timerTask.cancel();
			timerTask = new ScrollTimerTask();
			timer.schedule(timerTask, 100); 
		}
	}
	
	private void scrolltoPosition(){
		final int x = getScrollX();
		System.out.println("x = " + x);
		if(x % 140 != 0){
			post(new Runnable() {
				
				public void run() {
					if(x % 140 > 70){
						scrollTo((x / 140 + 1) * 140, 0);
					}else{
						scrollTo((x / 140) * 140, 0);
					}
					
				}
			});
			
		}
	}
	
	private class ScrollTimerTask extends TimerTask{
		public void run() {
			isAutoScolling = false;
			scrolltoPosition();			
		}
	}

}
